package com.design.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yijy on 2018/4/19.
 */
public class WechatServer implements Observerable {

    private WechatServer(){
        list = new ArrayList<Observer>();
    }

    private List<Observer> list;

    private String message;

    private static volatile WechatServer wechatServer;

    public static WechatServer getWechatServer(){
        if(wechatServer==null){
            synchronized(WechatServer.class){
                if(wechatServer==null){
                    wechatServer = new WechatServer();
                }
            }
        }
        return wechatServer;
    }

    @Override
    public void registerObserver(Observer o) {
        if(o!=null){
            if(!list.contains(o)){
                list.add(o);
            }
        }
    }

    @Override
    public void removeObserver(Observer o) {
        if(!list.isEmpty()){
            list.remove(o);
        }
    }

    @Override
    public void notifyObserver() {
        for (int i=0;i<list.size();i++){
            Observer observer = list.get(i);
            observer.update(message);
        }
    }

    public void setInfomation(String s){
        this.message = s;
        System.out.println("微信服务更新消息："+s);
        notifyObserver();
    }
}
